<?php
function error($data){//错误信息处理
	if(is_array($data)){
        foreach ($data as $key => $value) {
        	echo $value."<br>";
        }
    }else{
    	echo $data;
    }
}

function node_merge($node,$access=null,$pid=0){
    $arr=array();
    foreach($node as $key=>$value){
        if(is_array($access)){
            $value["access"]= in_array($value["id"],$access) ? 1 :0;
        }
        if($value["pid"]==$pid){
            $value['child']=node_merge($node,$access,$value["id"]);
            $arr[]=$value;
        }
    }

    return $arr;
}

/**
 * 将二维数组中的值转为一维数组的键
 * @param array $array
 * @param string $key
 * @param bool $repeat 是否存在键重复，键重复时将根据键生成数组
 * @return array
 */
function array_key_set($array, $key, $repeat = false)
{
    if (!$array) {
        return [];
    }
    $a = [];
    foreach ($array as $k => $v) {
        if ($repeat) {
            $a[$v[$key]][] = $v;
        } else {
            $a[$v[$key]] = $v;
        }
    }
    return $a;
}


function unit($uid){
    $userinfo=M("userinfo");
    $result=$userinfo->where(array("uid"=>$uid))->find();
    return $result["company"];
}

/**
 * 写入Excel
 * @param $file
 * @param $data
 * @return bool|string
 *
$Excel = new Excel();
$Excel->write('a.xlsx',[
'Sheet1'=>[
[1,2,3]
]
]);
 */
function write($file,$data){
    if(!$data||!$file||!( file_exists($file)?unlink($file):true )){
        return false;
    }
    $pathinfo = pathinfo($file);
    $path = realpath($pathinfo['dirname']);
//    $file=$path.DIRECTORY_SEPARATOR.$pathinfo['basename'];
//    $file = realpath($file);
    $sheet_id = 0;
    //创建excel操作对象
    $objPHPExcel = new \PHPExcel();
    //获得文件属性对象，给下文提供设置资源
    $objPHPExcel->getProperties()->setCreator("度咪")
        ->setLastModifiedBy("shadow")
//            ->setTitle("Input_Goods_message")
//            ->setSubject("主题1")
//            ->setDescription("随便一个描述了")
//            ->setKeywords("关键字 用空格分开")
        ->setCategory("分类 ");
    for($i=1;$i<count($data);$i++){
        $objPHPExcel->addSheet(new \PHPExcel_Worksheet($objPHPExcel,'sheet'.$i));
    }
    foreach($data as $sheetName => $sheetData){
        $Sheet = $objPHPExcel->setActiveSheetIndex($sheet_id);
        $Sheet->setTitle($sheetName);
        $Sheet->fromArray($sheetData);
        $sheet_id++;
    }
    try{
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, explode('.',$file)[1]=='xlsx'?'Excel2007':'Excel5');
        $objWriter->save($file);
    }catch (\Exception $e){
        return false;
    }
    return $file;
}


